﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Gizmox.WebGUI.Forms;
using System.Xml;

namespace PLACEHR.Web.Utilities
{
    class SalarySettings
    {
        static readonly string relativeFilePath = @"\Resources\Configuration\SalarySettings.xml";
        static readonly string physicalFilePath = string.Empty;
        static XmlDocument xdoc = new XmlDocument();

        static SalarySettings()
        {
            // Need to get physical file path here
            physicalFilePath = relativeFilePath;

            xdoc.Load(physicalFilePath);
        }

        public static string ReadValue(string xPath, string key)
        {
            try
            {
                if (string.IsNullOrEmpty(xPath))
                {
                    return xdoc.DocumentElement.Attributes[key].Value;
                }

                return xdoc.DocumentElement.SelectSingleNode(xPath).Attributes[key].Value;
            }
            catch (Exception ex)
            {
                // handler if add new function, but the setting file don't contain the node.
                // return 1 can avoid set null to the selected value of combobox
                return "1";
            }
        }

        public static bool UpdateSettings(string xPath, Dictionary<string, string> attributes)
        {
            if (attributes == null)
                return false;
            try
            {
                XmlElement xe = null;
                if (string.IsNullOrEmpty(xPath))
                    xe = xdoc.DocumentElement;
                else
                    xe = (XmlElement)xdoc.DocumentElement.SelectSingleNode(xPath);
                foreach (var item in attributes)
                {
                    xe.SetAttribute(item.Key, item.Value);
                }
                xdoc.Save(physicalFilePath);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return false;
        }

    }

}